package com.fafian.gdc.app.android;

import android.os.AsyncTask;
import android.os.Vibrator;
import android.view.View;
import android.view.View.OnClickListener;

import com.fafian.gdc.core.Command;
import com.fafian.gdc.socket.GDCSocket;
import com.fafian.gdc.socket.GDCSocketException;
import com.fafian.gdc.socket.SocketMessageResponse;

public class ButtonClickListener implements OnClickListener{
	
	private GDCServerPreferences preferences;
	private Vibrator vibrator;
	
	public ButtonClickListener(GDCServerPreferences preferences, Vibrator vibrator){
		this.vibrator = vibrator;
		setPreferences(preferences);
	
	}
	
	public void setPreferences(GDCServerPreferences preferences){
		this.preferences = preferences;
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
	    case R.id.button1:
	    	sendCommand( preferences, Command.PUSH_BUTTON1); 
	      break;
	    case R.id.button2:
	    	sendCommand( preferences, Command.PUSH_BUTTON2);
	      break;
	      default:
	    	  break;
		}
		
		
	}
	
	private void sendCommand(final GDCServerPreferences preferences, Command command){

		new AsyncTask<Command, Void , String>(){

			@Override
			protected String doInBackground(Command... params) {
				try{
					GDCSocket socket = null;
					try {
					
						socket = new GDCSocket(preferences.getServer(), preferences.getPortNumber());
					}
					catch (GDCSocketException e){
						socket = new GDCSocket(preferences.getDefaultHost(), preferences.getPortNumber());
					}
					SocketMessageResponse resp = socket.sendRequest(preferences.getApiKey(), params[0]);
					if (resp.isOK())
						vibrator.vibrate(250);
					socket.close();
					return resp.getExplanation();
				} catch (Exception e) {
					e.printStackTrace();
				}
				return null;
			}
			
		}.execute(command);
	}

	
		
}

